import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../services/user.dart';
import '../../services/sign.dart';
import 'package:dio/dio.dart';

import '../../services/event_bus.dart';

class AddressListPage extends StatefulWidget {
  AddressListPage({Key key}) : super(key: key);

  _AddressListPageState createState() => _AddressListPageState();
}

class _AddressListPageState extends State<AddressListPage> {
  List addressList = [];

  @override
  void initState() {
    super.initState();
    this._getAddressList();

    //监听增加收货地址的广播
    eventBus.on<AddressEvent>().listen((event) {
      // print(event.str);
      this._getAddressList();
    });
  }

  //监听页面销毁的事件
  dispose() {
    super.dispose();
    eventBus.fire(new CheckOutEvent('改收货地址成功...'));
  }

  //获取收货地址列表
  _getAddressList() async {
    //请求接口
    List userinfo = await User.getUserInfo();

    var tempJson = {"uid": userinfo[0]['_id'], "salt": userinfo[0]["salt"]};

    var sign = SignServices.getSign(tempJson);

    var api = 'api/addressList?uid=${userinfo[0]['_id']}&sign=$sign';

    var response = await Dio().get(api);
    // print(response.data["result"]);

    setState(() {
      this.addressList = response.data["result"];
    });
  }

  //修改默认收货地址
  _changeDefaultAddress(id) async {
    Navigator.of(context).pop();
  }

  //删除收货地址

  _delAddress(id) async {
    List userinfo = await User.getUserInfo();
    var tempJson = {
      "uid": userinfo[0]["_id"],
      "id": id,
      "salt": userinfo[0]["salt"]
    };

    var sign = SignServices.getSign(tempJson);

    var api = 'api/deleteAddress';
    await Dio()
        .post(api, data: {"uid": userinfo[0]["_id"], "id": id, "sign": sign});
    this._getAddressList(); //删除收货地址完成后重新获取列表
  }

  //弹出框
  _showDelAlertDialog(id) async {
    await showDialog(
        barrierDismissible: false, //表示点击灰色背景的时候是否消失弹出框
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("提示信息!"),
            content: Text("您确定要删除吗?"),
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              FlatButton(
                child: Text("确定"),
                onPressed: () async {
                  //执行删除操作
                  this._delAddress(id);
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            "地址管理",
              style: TextStyle(
              fontSize: 30.sp,
              fontWeight: FontWeight.bold),
          ),
          centerTitle: true,
        ),
        body: Container(
          padding: EdgeInsets.only(right: 20.w),
          color: Colors.white,
          child: Column(
            children: [
              Expanded(
                child: Container(
                  height: 500,
                  child: ListView.builder(
                    physics: BouncingScrollPhysics(),
                    itemCount: 10,
                    itemBuilder: (context, int index) {
                      return Column(
                        children: [
                          ListTile(
                            title: Text('收货人：王志强 18860474919'),
                            subtitle: Text('收货地址：安徽省淮南市潘集区王圩村新王伟2栋201安徽省淮南市潘集区王圩村新王伟2栋201'),
                          ),
                          Divider(),
                          Row(
                            children: [
                              Expanded(
                                child: RadioListTile(
                                  value: true,
                                  groupValue: '1',
                                  dense:true,
                                  title: Text('设为默认',style: TextStyle(
                                      color: Colors.black54,fontSize: 30.sp
                                  ),),
                                  onChanged: (value) {},
                                ),
                              ),
                              Row(
                                children: [
                                  Row(
                                    children: [
                                      Icon(Icons.edit,color: Colors.black54,),
                                      Text('编辑',style: TextStyle(
                                        color: Colors.black54
                                      ),),
                                    ],
                                  ),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Row(
                                    children: [
                                      Icon(Icons.delete,color: Colors.black54,),
                                      Text('删除',style: TextStyle(
                                          color: Colors.black54
                                      ),),
                                    ],
                                  ),
                                ],
                              )
                            ],
                          ),
                          Divider()
                        ],
                      );
                    },
                  ),
                ),
              ),
              Container(
                width: 750.w,
                height:120.w,
                padding: EdgeInsets.only(top:20.w,bottom: 20.w,right: 50.w,left: 50.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                  border:Border(
                    top: BorderSide(
                      color: Colors.red ,
                      width: 1.0
                    )
                  )
                ),
                child: FlatButton(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(20))),
                  color: Colors.red,
                  onPressed: () {
                    Navigator.of(context).pushNamed('/addressAdd');
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.location_on,color: Colors.white,),
                      Text(
                        '添加新地址',
                        style: TextStyle(color: Colors.white),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ));
  }
}
